<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      function myAxios(options) {
        console.log(options)
        const { url, method = 'get', data } = options
        return new Promise((resolve, reject) => {
          // 发起请求（xhr）
          const xhr = new XMLHttpRequest()
          xhr.open(method, url)
          xhr.setRequestHeader('content-type', 'application/json')
          xhr.addEventListener('load', function () {
            // console.log(xhr.response)
            resolve(xhr.response)
          })
          xhr.send(JSON.stringify(data))
        })
      }
      // 添加图书
      const p1 = myAxios({
        url: 'http://ajax-api.itheima.net/api/books',
        method: 'post',
        data: {
          bookname: '水浒传',
          author: '施耐庵',
          publisher: '人民出版社',
        },
      })
      // 修改图书
      const p2 = myAxios({
        url: 'http://ajax-api.itheima.net/api/books/3654',
        method: 'put',
        data: {
          bookname: '我在修改图书',
          author: '施耐庵',
          publisher: '人民出版社',
        },
      })
      // 删除图书
      const p3 = myAxios({
        url: 'http://ajax-api.itheima.net/api/books/3812',
        method: 'DELETE',
      })

      // 等待所有接口都请求成功
      //   Promise.all([p1, p2, p3]).then((res) => {
      //     console.log(res)
      //     // 渲染页面
      //     // ……
      //   })

      // 等待第一个
      Promise.race([p1, p2, p3]).then((res) => {
        console.log(res)
      })
    </script>
  </body>
</html>
